<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../static/lib/layui-v2.9.8/css/layui.css" media="all">
    <link rel="stylesheet" href="./../../static/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">


        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-primary layui-border-green layui-btn-xs data-count-edit"
               lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-primary layui-border-red data-count-delete"
               lay-event="delete">删除</a>
        </script>
        <script type="text/html" id="toolbarUser">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-primary layui-border-green layui-btn-sm data-add-btn"
                        lay-event="add"> 新增
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-primary layui-border-red data-delete-btn"
                        lay-event="batch_delete"> 批量删除
                </button>
            </div>
        </script>
    </div>
</div>
<script src="../../../static/lib/layui-v2.9.8/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table'], function () {
            var $ = layui.jquery,
                form = layui.form,
                table = layui.table;

            var userID = $("#login_user", parent.document).text();

            var token = "{{ csrf_token }}"
            $.ajaxSetup({
                headers: {
                    'X-CSRFTOKEN': `${token}`,
                    'AUTHORIZATION': 'Bearer ' + localStorage.token,
                }, // JWTAuthentication.authenticate()方法获取 header = request.META.get(api_settings.AUTH_HEADER_NAME),
            });


            $.ajaxSetup({
                complete: function (XMLHttpRequest, textStatus) {
                    if (XMLHttpRequest.status === 401) {  // 401 表示未授权，即 token 无效
                        layer.msg('授权已过期，需重新登陆', {icon: 2, time: 2000}, function () {
                            window.location.href = '/login';
                        })
                    }
                }
            });

            window.parent_msg = function (msg) {
                layer.msg(msg, {icon: 1})
            }

            table.render({
                elem: '#currentTableId',
                url: '/product_manage_list',
                method: 'get',
                toolbar: '#toolbarUser',
                defaultToolbar: ['filter', 'exports', 'print'],
                cols: [[
                    {type: "checkbox", width: 50},
                    {field: 'count', width: 100, title: '序号', align: 'center', sort: true, type: 'numbers'},
                    {field: 'id', width: 100, title: 'ID', align: 'center', hide: true},
                    {field: 'name', width: 200, title: '名字', align: 'center'},
                    {field: 'specification', width: 200, title: '规格', align: 'center'},
                    {field: 'price', width: 360, title: '价格', align: 'center'},
                    {field: 'quantity', width: 360, title: '数量', align: 'center'},
                    {title: '操作', minWidth: 200, toolbar: '#currentTableBar', align: "center"}
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 10,
                page: true,
                skin: 'row',
                even: true,
                parseData: function (res) { //res 即为原始返回的数据
                    console.log(res)
                },
                before: function (res, curr, count) {
                },
                done: function (res, curr, count) {

                }

            });

            // 监听搜索操作
            form.on('submit(data-search-btn)', function (data) {
                console.log(data.field);
                var result = JSON.stringify(data.field);

                //执行搜索重载
                table.reload('currentTableId', {
                    page: {
                        curr: 1
                    }
                    , where: {
                        Params: result
                    }
                }, 'data');

                return false;
            });

            /**
             * toolbar监听事件
             */
            table.on('toolbar(currentTableFilter)', function (obj) {
                if (obj.event === 'add') {  // 监听添加操作
                    var index = layer.open({
                        title: '新增商品',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['40%', '60%'],
                        content: '/product_manage_add',
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                } else if (obj.event === 'batch_delete') {
                    let checkStatus = table.checkStatus('currentTableId')
                    if (checkStatus.data.length === 0) {
                        layer.msg('没有选择删除数据')
                        return false;
                    }
                    let ids = []
                    $.each(checkStatus.data, function (index, item) {
                        ids.push(item['id'])
                    })
                    layer.confirm('真的删除行么?', {icon: 3, title: '确认删除'}, function (index) {
                        layer.close(index);
                        $.ajax({
                            url: '/product_manage_del',
                            type: "POST",
                            dataType: "JSON",
                            data: {'id': ids, 'batch': '1'},
                            traditional: true,
                            success: function (result) {
                                if (result.success) {
                                    layer.msg(result.msg, {icon: 1});
                                } else {
                                    layer.msg(result.msg, {icon: 2});
                                }
                            },
                            error: function (result) {
                                alert("接口错误！！");
                            }
                        });
                        table.reload('currentTableId')
                        return false;
                    });
                }
            })
            //监听表格复选框选择
            table.on('checkbox(currentTableFilter)', function (obj) {
                console.log(obj)
            });

            table.on('tool(currentTableFilter)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    var index = layer.open({
                        title: '编辑商品',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['40%', '60%'],
                        content: '/product_manage_edit',
                        success: function (layero, index) {
                            let iframe = window['layui-layer-iframe' + index];
                            iframe.parent_to_child(obj);
                        }
                    });
                    $(window).on("resize", function () {
                    });
                    return false;
                } else if (obj.event === 'delete') {
                    layer.confirm('真的删除行么?', {icon: 3, title: '确认删除'}, function (index) {
                        obj.del();
                        layer.close(index);
                        $.ajax({
                            url: '/product_manage_del',
                            type: "POST",
                            dataType: "JSON",
                            data: {'id': obj.data.id, 'batch': '0'},
                            traditional: true,
                            success: function (result) {
                                if (result.success) {
                                    layer.msg(result.msg, {icon: 1});
                                } else {
                                    layer.msg(result.msg, {icon: 2});
                                }
                            },
                            error: function (result) {
                                alert("接口错误！！");
                            }
                        });
                        return false;
                    });
                }
            });


            table.on('edit(currentTableFilter)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                // console.log(obj.value); //得到修改后的值
                // console.log(obj.field); //当前编辑的字段名
                console.log(obj.data); //所在行的所有相关数据
                //传给后台
                var URL = '/role/' + obj.data.id + '/';
                $.ajax({
                    url: URL,
                    type: "put",
                    data: obj.data,
                    success: function (result) {
                        if (result.success) {
                            layer.msg(result.msg, {icon: 1});
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }

                    },
                    error: function (result) {
                        alert("接口错误！！");
                    }
                });
                return false;


            });

            // 监听开关
            form.on('switch(role-enable)', function (obj) {
                // console.log(obj.elem.attributes['roleID'].nodeValue);
                // console.log(obj);
                let roleId = obj.elem.attributes['roleID'].nodeValue;

                let operate
                if (obj.elem.checked) {
                    operate = 'enable'
                } else {
                    operate = 'disable'
                }
                let loading = layer.load()

                $.ajax({
                    url: "/role/enable/",
                    type: "put",
                    data: {
                        id: roleId,
                        enable: operate
                    },
                    success: function (result) {
                        layer.close(loading)
                        if (result.success) {
                            layer.msg(result.msg, {icon: 1});
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }
                    },
                    error: function (result) {
                        alert("接口错误！！");
                    }
                });
                return false;

            })

            // window.refresh = function (param) {
            //   table.reload('currentTableId', { where: params })
            // }


        }
    );
</script>

</body>
</html>